package cluster

import (
	"fmt"
	"runtime"
	"strings"

	"github.com/hashicorp/memberlist"
	"github.com/spf13/cast"
)

type Member memberlist.Node

func (m Member) ServPort() uint32 {
	_, port, _ := m.NameAnalysis()
	return port
}

func (m Member) ServAddress() string {
	port := m.ServPort()
	return fmt.Sprintf("%s:%d", m.Addr.String(), port)
}

func (m Member) CtlPort() uint32 {
	_, _, port := m.NameAnalysis()
	return port
}

func (m Member) CtlAddress() string {
	port := m.CtlPort()
	return fmt.Sprintf("%s:%d", m.Addr.String(), port)
}

func (m Member) StartUpTime() int64 {
	startuptime, _, _ := m.NameAnalysis()
	return startuptime
}

func (m Member) NameAnalysis() (startuptime int64, servport uint32, ctlport uint32) {
	strs := strings.SplitN(m.Name, Content_Separator, 3)
	startuptime = cast.ToInt64(strs[0])
	servport = cast.ToUint32(strs[1])
	ctlport = cast.ToUint32(strs[2])
	return
}

func MemStats() (ms runtime.MemStats) {
	runtime.ReadMemStats(&ms)
	return
}
